package cc.yaomm.common.basic.captcha.handler;

import cc.yaomm.common.basic.captcha.config.CaptchaProperties;
import cc.yaomm.common.basic.captcha.generator.CaptchaGenerator;
import cc.yaomm.common.basic.domain.KeyValue;
import cc.yaomm.common.basic.enums.CaptchaType;
import cc.yaomm.common.basic.exception.BusinessException;
import cc.yaomm.common.basic.base.SuperSmsTemplate;
import cc.yaomm.common.basic.sms.SmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by XQL on 2020/5/14.
 */
public class SmsCaptchaHandler implements CaptchaHandler {

    @Autowired
    SmsService smsService;

    @Autowired
    CaptchaGenerator captchaGenerator;

    @Autowired
    CaptchaProperties captchaProperties;

    @Autowired
    StringRedisTemplate redisTemplate;

    public StringRedisTemplate getRedisTemplate() {
        return redisTemplate;
    }

    /**
     * <p>@Description: 短信发送</p>
     * <p>@Author: QiLin.Xing </p>
     * <p>@Date: 2020/5/17 23:33 </p>
     * <p>@Version: 1.0
     *
     * @param payload 手机号
     * @param params  参数说明：第一个参数必须为模板ID；第二参数必须为验证码参数的key；后面的参数两两一对（key-value)
     * @return
     */
    @Override
    public String generate(CaptchaType captchaType, String payload, Object... params) {
        //判断参数是否为空
        if (params == null || params.length == 0) {
            throw new BusinessException("参数不能为空");
        }

        SuperSmsTemplate smsTemplate = null;
        //判断第一个是否为短信模板参数
        if (params[0] instanceof SuperSmsTemplate) {
            smsTemplate = (SuperSmsTemplate) params[0];
        }

        //获取验证码
        KeyValue<String, String> captcha = captchaGenerator.generate();

        //生成验证码
        Map<String, Object> paramsMap = new HashMap<>();
        //判断参数是否只有一个
        if (params.length == 1) {
            paramsMap.put("code", captcha.getKey());
        } else {
            paramsMap.put(params[1].toString(), captcha.getKey());
            if (params.length % 2 == 0) {
                for (int i = 2; i < params.length; i = i + 2) {
                    paramsMap.put(params[i].toString(), params[i + 1]);
                }
            } else {
                throw new BusinessException("参数设置有错误，参数长度必须为偶数");
            }
        }

        //发送短信
        boolean result = smsService.send(payload, paramsMap, smsTemplate);
        if (result) {
            //缓存验证 设置有效期
            this.setCache(captchaType, payload, captcha.getValue(), captchaProperties.getExpire());
        }

        return String.valueOf(result);
    }
}
